$(function(){
	var
		userName = $('#user_name'),
		userLocation = $('#user_location'),
		userType = $('#user_type'),
		userRate = $('#user_rate'),
		userRateValue = $('#user_rate_value'),
		userId = $('#user_id');
		vendorId = $('#vendor-id');
		currencyClient = $('#currency_client');
		exchangeCurrencyClient = $('#exchange_currency_client'),
		currencyVendor = $('#currency_vendor'),
		exchangeCurrencyVendor = $('#exchange_currency_vendor'),
		exchange = $('#exchange'),
		priceNetVendor  = $('#price_net_vendor'),
		priceNet = $('#price_net'),
		priceNetText = $('#price_net_text'),
		priceGross = $('#price_gross'),
		priceGrossTransaction = $('#price_gross_transaction'),
		priceGrossTransactionText = $('#price_gross_transaction_text'),
		profitVendor = $('#profit_vendor'),
		profitClient = $('#profit_client'),
		vendorRate = $('#vendor_rate'),
		commission = $('#commission'),
		commissionText = $('#commission_text'),
		priceGrossComment = $('#price_gross_comment'),
		priceGrossCommentBlock = $('#price_gross_comment_block'),
		priceGrossOldValue = '',
		userIdOldValue = '',
		priceNetVendorOldValue = '',
		exchangeOldValue = ''
	;

	if ($('#vendor-edit-form').length > 0 || $('#vendor-filter-form').length > 0) {

		userId.focus(function() {
			userIdOldValue = $(this).val();
		});

		userId.blur(function() {
			var value = $(this).val();
			if (userIdOldValue != value) {
				$.ajax({
					async   : false,
					type    : "GET",
					url     : "/a_admin/bookingvendor.getUserName",
					dataType: "json",
					data    : {user_id: value, vendor_id:  vendorId.val()},
					success : function(data) {
						if (data.error == 0) {
							var name = data.name;
							if (data.company) {
								name += ' (' + data.company + ')';
							}
							userName.val(name).next('label').remove();

							userLocation.val(data.location).attr('disabled', 'disabled').next('label').remove();

							userType.val(data.type).attr('disabled', 'disabled').next('label').remove();

							userRate.val(data.rate).attr('disabled', 'disabled').next('label').remove();

							userRateValue.val(data.rateValue).next('label').remove();
							if (data.rate == 0) {
								userRateValue.attr('disabled', 'disabled').show();
							} else {
								userRateValue.hide();
							}
						} else {
							userName.val('');
							userLocation.val('').removeAttr('disabled');
							userType.val('').removeAttr('disabled');
							userRate.val('').removeAttr('disabled');
							userRateValue.val('').attr('disabled', 'disabled').hide();
						}
						if (currencyClient.val() != '' && currencyVendor.val() != '') {
							setExchange(currencyClient.val(), currencyVendor.val(), userLocation.val());
						}

						setVendorRateValue();

						if (priceNetVendor.val()) {
							setPrices(priceNetVendor.val(), '');
						}
					}
				});
			}
		});

		var autocompleteUrl = '';

		vendorId.change(function() {
			var s = $(this);
			var t = $('#selector-vendor-country'), p = {id: s.val()};
	        t.html('<option value="">Загрузка...</option>');
	        t.attr('disabled', 'disabled');
	        $.get('/a_ajax/location.getVendorCountries', p, function (data) {
	            t.attr('disabled', '');
	            var h = '';
	            h += '<option value="" selected="selected" class="first">' + s.attr('deftext') + '</option>';
	            t.html(h + data);
	        });
	        if (s.val()) {
	        	userId.removeAttr('disabled');
	        	userName.removeAttr('disabled');
	        	if (! userId.val()) {
	        		userLocation.removeAttr('disabled');
					userType.removeAttr('disabled');
					userRate.removeAttr('disabled');
	        	}
				autocompleteUrl = 'bookingvendor.autocomplete?vendor_id=' + s.val();
				setAutocomplete(autocompleteUrl);
				setVendorRateValue();
				setRateValue();
	        } else {
				userId.val('').attr('disabled', 'disabled').next('label').remove();
				userName.val('').attr('disabled', 'disabled');
				userLocation.val('').attr('disabled', 'disabled');
				userType.val('').attr('disabled', 'disabled');
				userRate.val('').attr('disabled', 'disabled');
				userRateValue.val('').attr('disabled', 'disabled').hide();
	        }
	    });

		if ($('#vendor-edit-form').length > 0) {
			if (vendorId.val()) {
				autocompleteUrl = 'bookingvendor.autocomplete?vendor_id=' + vendorId.val();
			}
		} else if ($('#vendor-filter-form').length > 0) {
			autocompleteUrl = 'bookingvendor.autocompleteFilter';

			$('#btn-export-to-excel').click(function() {
				$(this).parents('form').attr('action', $('#export-to-excel-url').val()).submit();
			});

			$('#btn-filter').click(function() {
				$(this).parents('form').attr('action', $('#filter-url').val()).submit();
			});
		}

		function setAutocomplete(autocompleteUrl) {
			userName.autocomplete(autocompleteUrl, {
				max: 10,
				matchSubset: 1,
				autoFill: false,
				matchContains: 1,
				matchSubset: 1,
				cacheLength: 10,
				maxItemsToShow: 10
			});
		}

		if (autocompleteUrl) {
			setAutocomplete(autocompleteUrl);
		}

		userName.result(function(event, data, formatted) {
			userId.val( (data && data[1] != '') ? data[1] : '').next('label').remove();
			userLocation.val(data[2]).attr('disabled', 'disabled').next('label').remove();
			userType.val(data[3]).attr('disabled', 'disabled').next('label').remove();
			userRate.val(data[4]).attr('disabled', 'disabled').next('label').remove();
			userRateValue.val(data[5]).attr('disabled', 'disabled').next('label').remove();

			if (data[5] == 0) {
				userRateValue.attr('disabled', 'disabled').show();
			} else {
				userRateValue.hide();
			}

			if (data[4] == 0) {
				userRateValue.show();
			}
			if (currencyClient.val() != '' && currencyVendor.val() != '') {
				setExchange(currencyClient.val(), currencyVendor.val(), userLocation.val());
			}

			setVendorRateValue();

			if (priceNetVendor.val() != '') {
				setPrices(priceNetVendor.val(), '');
			}
		});

		userName.blur(function() {
			if (! $(this).val()) {
				userId.val('').removeAttr('disabled');

				userLocation.val('').removeAttr('disabled');

				userType.val('').removeAttr('disabled');

				userRate.val('').removeAttr('disabled');

				userRateValue.hide();

				userRateValue.val('');
			}
			if (currencyClient.val() != '' && currencyVendor.val() != '') {
				setExchange(currencyClient.val(), currencyVendor.val(), userLocation.val());
			}

			setVendorRateValue();

			if (priceNetVendor.val() != '') {
				setPrices(priceNetVendor.val(), '');
			}
		});
	}
	if ($('#vendor-edit-form').length > 0) {
		var
			bool = true,
			mesReq = 'REQUIRED_FIELD'.translate(),
			mesNumber = 'INPUT_CORRECT_NUMBER'.translate(),
			mes_min = 'INPUT_VALUE_MORE_0'.translate(),
			mes_max = 'VALUE_MUST_BE_LESS_100'.translate(),
			mes_positive = 'VALUE_MUST_BE_POSITIVE'.translate(),
			mes_currency_net_vendor = 'CURRENCY_VENDOR_REQUIRED'.translate(),
			mes_price_net_vendor = 'VALUE_NET_REQUIRED'.translate(),
			mes_currency_gross_transaction = 'CURRENCY_VENDOR_REQUIRED'.translate(),
			mes_price_gross_transaction = 'VALUE_GROSS_REQUIRED'.translate()
		;
		$.validator.messages.required = mesReq;
		$.validator.messages.number = mesNumber;

		$('#vendor-edit-form').validate({
			errorClass: 'invalid',
			messages: {
				user_id: {
					min: mes_positive
				},
				commission: {
					min: mes_min,
					max: mes_max
				},
				price_gross: {
					min: mes_min
				},
				price_net: {
					min: mes_min,
					required: mes_price_net_vendor
				},
				currency_net_vendor: {
					required: mes_currency_net_vendor
				},
				price_net_vendor: {
					min: mes_min
				},
				currency_gross_transaction: {
					required: mes_currency_gross_transaction
				},
				price_gross_transaction: {
					required: mes_price_gross_transaction,
					min: mes_min
				},
				currency: {
					required: mes_currency_net_vendor
				},
				currency_net: {
					required: mes_currency_net_vendor
				},
				user_rate: {
					min: mesReq
				}
			},
			rules: {
				user_id: {
					min: 1
				},
				commission: {
					min: 0,
					max: 100
				},
				price_gross: {
					min: 0
				},
				price_net: {
					min: 0
				},
				price_net_vendor: {
					min: 0
				},
				price_gross_transaction: {
					min: 0
				},
				vendor_id: {
					url: false
				},
				user_rate: {
					min: 0
				}
			},
			errorPlacement: function(error, element) {
				if (element.hasClass("date-picker"))
					error.appendTo(element.parents('.body'));
				else if (element.attr("name") == 'exchange')
					error.appendTo('#exchange_placeholder');
				else
					error.insertAfter(element);
			}
		});

		$('#departure_date').datepicker('change', {
			'minDate': Date.fromString($('#arrival_date').val())
		});

		function datesCompare() {
			if (Date.fromString($('#arrival_date').val()) > Date.fromString($('#departure_date').val()) && Date.fromString($('#departure_date').val()) > null) {
				bool = false;
				alert('DATES_ARRIVE_COMPARE'.translate());
				$('#arrival_date').focus();
			} else {
				bool = true;
			}
		}
		$('#arrival_date').change(function() {
			$('#departure_date').datepicker('change', {
				'minDate': Date.fromString($('#arrival_date').val())
			});
			datesCompare();
		});
		$('#departure_date').change(function() {
			datesCompare();
		});

		$('#vendor-edit-form').submit(function() {
			datesCompare();
			return bool;
		});
	}

	var ajaxLoaderImg = new Image();
	ajaxLoaderImg.src = "/i/ajax-loader-small.gif";
	var ajaxLoader = '<img id="ajaxLoader" src="/i/ajax-loader-small.gif" width="16" height="16" alt="" />';

	$('input#paid-to-vendor').click(function() {
		$this = $(this);
		var bookingVendorId = parseInt($('#booking-vendor-id').text());
		$this.next('a').after(ajaxLoader);
		$.ajax({
			async   : false,
			type    : "GET",
			url     : "/a_admin/bookingvendor.changePaidToVendor",
			dataType: "json",
			data    : {booking_vendor_id: bookingVendorId, paid_to_vendor: this.checked},
			success : function(data){
				$('#ajaxLoader').remove();
			},
			error : function() {
				alert('Error with requesting ajax data.');
				$('#ajaxLoader').remove();
			}
		});
	});

	var
		paymentDateInput = $('#payment_date'),
		paymentDateBlock = $('.payment_date'),
		paymentStatus = $('#payment_status')
	;

	showPaymentDateBlock(paymentStatus.val());

	paymentStatus.change(function() {
		$this = $(this);
		showPaymentDateBlock($this.val());
	});

	function showPaymentDateBlock(paymentStatus) {
		if (paymentStatus == 'PAID') {
			paymentDateInput.addClass('required');
			paymentDateBlock.show();
		} else {
			paymentDateBlock.hide();
			paymentDateInput.val('');
			paymentDateInput.removeClass('required');
		}
	}

	if (! vendorId.val()) {
		userId.attr('disabled', 'disabled');
		userName.attr('disabled', 'disabled');
	}

	userRate.change(function() {
		var value = $(this).val();
		if (value == 0) {
			userRateValue.val('').removeAttr('disabled').show();
		} else {
			userRateValue.hide().val('').attr('disabled', 'disabled').next('label').remove();
		}
	});

	currencyClient.change(function() {
		var text = $(this).find('option:selected').text();
		if ($(this).val() != '') {
			exchangeCurrencyClient.text(text);
			if (currencyVendor.val() != '') {
				setExchange($(this).val(), currencyVendor.val(), userLocation.val());
				if (priceNetVendor.val() != '') {
					setPrices(priceNetVendor.val(), '');
				}
			}
		} else {
			exchange.val('').attr('disabled', 'disabled');
			exchangeCurrencyClient.text('?');
		}
	});

	currencyVendor.change(function() {
		var text = $(this).find('option:selected').text();
		if ($(this).val() != '') {
			exchangeCurrencyVendor.text(text);
			if (currencyClient.val() != '') {
				setExchange(currencyClient.val(), $(this).val(), userLocation.val());
				if (priceNetVendor.val() != '') {
					setPrices(priceNetVendor.val(), '');
				}
			}
		} else {
			exchange.val('').attr('disabled', 'disabled');
			exchangeCurrencyVendor.text('?');
		}
	});

	function setExchange(currencyClient, currencyVendor, userLocation) {
		$.ajax({
			async   : false,
			type    : "GET",
			url     : "/a_admin/bookingvendor.getExchange",
			dataType: "json",
			data    : {currency_client: currencyClient, currency_vendor: currencyVendor, user_location: userLocation},
			success : function(data) {
				if (data.error == 0) {
					exchange.val(data.exchange).removeAttr('disabled');
				}
			}
		});
	}

	priceNetVendor.focus(function() {
		priceNetVendorOldValue = $(this).val();
	});

	priceNetVendor.blur(function() {
		if ($(this).val() != priceNetVendorOldValue && ! isNaN($(this).val())) {
			priceGrossComment.attr('disabled', 'disabled').val('');
			priceGrossCommentBlock.hide();
			setPrices($(this).val(), '');
		}
	});

	priceGross.focus(function() {
		priceGrossOldValue = $(this).val();
	});

	priceGross.blur(function() {
		if ($(this).val() != priceGrossOldValue && $(this).val() != '' && ! isNaN($(this).val())) {
			setPrices(priceNetVendor.val(), $(this).val());
			priceGrossComment.removeAttr('disabled');
			priceGrossCommentBlock.show();
		}
	});

	exchange.focus(function() {
		exchangeOldValue = $(this).val();
	});

	exchange.blur(function() {
		if ($(this).val() != exchangeOldValue && ! isNaN($(this).val())) {
			setPrices(priceNetVendor.val(), '');
		}
	});

	function setPrices(priceNetVendorValue, priceGrossValue) {
		var
			priceNetVendorRes = priceNetVendorValue,
			priceNetClientRes =  priceNetVendorRes * exchange.val(),
			priceGrossClientRes = '',
			priceGrossVendorWithRateVendor = '',
			priceGrossVendorRes = '',
			comissionRes = ''
		;
		if (! priceGrossValue) {
			priceGrossVendorWithRateVendor = priceNetVendorRes - 0 + ((vendorRate.val() / 100) * priceNetVendorRes);
			priceGrossVendorRes = priceGrossVendorWithRateVendor - ((userRateValue.val() / 100) * priceGrossVendorWithRateVendor);
			priceGrossClientRes = priceGrossVendorRes * exchange.val();
			priceGrossClientRes = Math.ceil(priceGrossClientRes.toFixed(3));
			priceGross.val(priceGrossClientRes.toFixed(2)).next('label').remove();
		} else {
			if (exchange.val()) {
				priceGrossVendorRes = priceGrossValue / exchange.val();
			} else {
				priceGrossVendorRes = 0;
			}
			priceGrossClientRes = priceGrossValue;
		}

		priceNet.val(priceNetClientRes.toFixed(2));
		priceNetText.text(priceNetClientRes.toFixed(2));

		priceGrossTransaction.val(priceGrossVendorRes.toFixed(2));
		priceGrossTransactionText.text(priceGrossVendorRes.toFixed(2));

		profitVendor.text((priceGrossVendorRes - priceNetVendorRes).toFixed(2));
		profitClient.text((priceGrossClientRes - priceNetClientRes).toFixed(2));

		if (priceNet.val() > 0) {
			comissionRes = (((priceGross.val() / priceNet.val()) * 100)-100).toFixed(2);
			commissionText.text(comissionRes + '%');
			commission.val(comissionRes);
		}
	}

	userRate.change(function() {
		setRateValue();
	});

	function setRateValue() {
		if ((userId.val()) || (! userId.val())) {
			$.ajax({
				async   : false,
				type    : "GET",
				url     : "/a_admin/bookingvendor.getRateValue",
				dataType: "json",
				data    : {vendor_id: vendorId.val(), user_rate: userRate.val(), user_location: userLocation.val(), user_id: userId.val()},
				success : function(data) {
					if (data.error == 0) {
						userRateValue.val(data.rateValue);
					}
				}
			});

			if (priceNetVendor.val()) {
				setPrices(priceNetVendor.val(), '');
			}
		}
	}

	function setVendorRateValue() {
		$.ajax({
			async   : false,
			type    : "GET",
			url     : "/a_admin/bookingvendor.getVendorRate",
			dataType: "json",
			data    : {vendor_id: vendorId.val(), user_location: userLocation.val()},
			success : function(data) {
				if (data.error == 0) {
					vendorRate.val(data.vendorRate);
				}
			}
		});
	}

	userLocation.change(function() {
		if (currencyClient.val() != '' && currencyVendor.val() != '') {
			setExchange(currencyClient.val(), currencyVendor.val(), $(this).val());
			setVendorRateValue();
			setRateValue();
		}
	});

	userRateValue.blur(function() {
		if (priceNetVendor.val()) {
			setPrices(priceNetVendor.val(), '');
		}
	});

});